package com.heima.wemedia.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        //参数检查  判断文件是否传输过来 ,用户是否登录(判断userId是否存在), 文件的格式
        if (file == null || file.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的素材!");
        }
        //拿到原始文件名称
        String filename = file.getOriginalFilename();
        //分割文件名
        String fileFfix = filename.substring(filename.lastIndexOf("."));
        //判断格式
        if (!checkFileFfix(fileFfix)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文件格式错误!请重新上传!");
        }
        //判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录!");
        }
        //将文件上传到oss  得到oss路径
        //设置文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            newFileName = fileStorageService.store(prefix, newFileName + fileFfix, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败" + e.getMessage());
        }
        //创建素材对象, 存入到素材表
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(newFileName);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());

        //保存素材
        this.save(wmMaterial);
        wmMaterial.setUrl(webSite + newFileName);
        //返回数据注意 , data: wmMaterl  将图片路径补全
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 分页查询素材列表,按照发布时间降序排序
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //校验参数
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录!");
        }
        //封装查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery();
        if (WemediaConstants.COLLECT_MATERIAL.equals(dto.getIsCollection())) {
            wrapper.eq(WmMaterial::getIsCollection, WemediaConstants.COLLECT_MATERIAL);
        }
        //查询当前用户上传的文件
        wrapper.eq(WmMaterial::getUserId, user.getId());
        //按照发布时间降序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //添加分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        //完成分页实现
        IPage<WmMaterial> iPage = this.page(page, wrapper);
        List<WmMaterial> records = iPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        //封装返回结果  在图片上加前缀
        return new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), records);
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 根据id删除素材图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1 参数校验 判断id是否为空
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial material = getById(id);
        //判断id是否被引用
        if (material == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "没有找到该图片的记录");
        }
        //创建查询条件构造器
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        //添加条件
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        //查询表中是否存在该素材
        Integer result = wmNewsMaterialMapper.selectCount(wrapper);
        //判断结果是否大于1
        if (result > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "没有找到该素材");
        }
        // 根据id删除素材库
        removeById(id);
        // 删除图片OSS
        fileStorageService.delete(material.getUrl());
        // 3 封装结果 , 返回删除成功结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏和取消收藏
     *
     * @param id   素材id
     * @param type 收藏的类型: 收藏 1 取消收藏 0
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //判断参数 id是否为空
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数错误!");
        }
        //通过id获取素材对象
        WmMaterial material = getById(id);
        //判断当前对象是否为null
        if (material == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该素材不存在,请稍后再试!");
        }
        //通过工具类拿出登录用户id
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //判断material对象中的用户id和从工具类中拿出的用户id是否相同
        if (!material.getUserId().equals(uid)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "只允许收藏自己上传的素材!请尝试其他素材!");
        }
        //修改material的状态
        material.setIsCollection(type);
        //保存material的修改信息
        updateById(material);
        //返回最终结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 判断文件格式是否复合规则
     *
     * @param fileFfix 截取后的文件后缀
     * @return 布尔值判断
     */
    private boolean checkFileFfix(String fileFfix) {

        //判断是否拿到文件后缀
        if (StringUtils.isBlank(fileFfix)) {
            return false;
        }
        //创建文件格式集合
        List<String> list = Arrays.asList(".jpg", ".png", ".gif", ".jpeg");
        //遍历集合
        boolean flag = false;
        for (String fileName : list) {
            if (fileFfix.equals(fileName)) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}